<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\MoneyBook;
use App\Models\MoneyBookUser;
use App\Models\MoneyCategory;
use App\Models\MoneySubCategory;
use App\Models\User;
use App\Models\BookInvitation;

class MoneyBookController extends Controller
{
    /**
     * 获取用户的所有账本
     */
    public function getBooks()
    {
        try {
            $user = Auth::user();

            $books = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->with(['users' => function($query) use ($user) {
                $query->where('user_id', $user->id);
            }, 'transactions' => function($query) {
                $query->whereMonth('transaction_date', now()->month)
                      ->whereYear('transaction_date', now()->year);
            }])->get();

            $booksData = $books->map(function($book) use ($user) {
                $monthlyIncome = $book->transactions->where('type', MoneyCategory::TYPE_INCOME)->sum('amount');
                $monthlyExpense = $book->transactions->where('type', MoneyCategory::TYPE_EXPENSE)->sum('amount');

                // 获取用户在该账本中的角色
                $userRole = $book->users->first()->pivot->role ?? 'member';

                // 如果是账本创建者，角色显示为owner/creator
                if ($book->user_id == $user->id) {
                    $userRole = 'owner';
                }

                return [
                    'id' => $book->id,
                    'name' => $book->name,
                    'icon' => $book->icon ?? '📘',
                    'member_count' => $book->users->count(),
                    'description' => $book->description,
                    'is_default' => $user->default_book_id == $book->id, // 修复：通过用户的default_book_id判断
                    'role' => $userRole,
                    'monthly_income' => $monthlyIncome,
                    'monthly_expense' => $monthlyExpense,
                    'created_at' => $book->created_at->format('Y-m-d H:i:s'),
                ];
            });

            return response()->json([
                'success' => true,
                'books' => $booksData
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取账本列表失败'
            ], 500);
        }
    }

    /**
     * 创建新账本
     */
    public function store(Request $request)
    {
        try {
            $user = Auth::user();

            // 验证输入数据
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:50',
                'description' => 'nullable|string|max:255',
                'icon' => 'nullable|string|max:10',
            ], [
                'name.required' => '账本名称不能为空',
                'name.max' => '账本名称不能超过50个字符',
                'description.max' => '账本描述不能超过255个字符',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => '验证失败',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 非会员用户账本数量限制
            if (!$user->isMember()) {
                $booksCount = $user->createdBooks()->count();
                if ($booksCount >= non_member_limits['max_books']) {
                    return response()->json([
                        'success' => false,
                        'message' => '非会员用户最多创建'.non_member_limits['max_books'].'个账本',
                        'redirect_to' => route('membership.benefits')
                    ], 403);
                }
            }

            DB::beginTransaction();

            // 创建账本
            $book = MoneyBook::create([
                'name' => $request->name,
                'icon' => $request->icon ?? '📘',
                'description' => $request->description,
                'user_id' => $user->id,
                'is_default' => 0,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '账本创建成功',
                'book' => [
                    'id' => $book->id,
                    'name' => $book->name,
                    'description' => $book->description,
                    'is_default' => $book->is_default,
                ]
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => '创建账本失败，请重试'
            ], 500);
        }
    }

    /**
     * 设置默认账本
     */
    public function setDefault($id)
    {
        try {
            $user = Auth::user();

            // 验证账本权限
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($id);

            DB::beginTransaction();

            // 取消其他账本的默认状态
            MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->update(['is_default' => false]);

            // 设置当前账本为默认
            $book->update([
                'is_default' => true,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => '默认账本设置成功'
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => '设置默认账本失败，请重试'
            ], 500);
        }
    }

    /**
     * 删除账本
     */
    public function destroy($id)
    {
        try {
            $user = Auth::user();

            // 验证账本权限（只有管理员可以删除）
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id)
                      ->where('role', MoneyBookUser::ROLE_ADMIN);
            })->findOrFail($id);

            // 检查是否为默认账本
            if ($book->is_default) {
                return response()->json([
                    'success' => false,
                    'message' => '不能删除默认账本，请先设置其他账本为默认'
                ], 422);
            }

            // 删除账本（级联删除相关数据）
            $book->delete();

            return response()->json([
                'success' => true,
                'message' => '账本删除成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '删除账本失败，请重试'
            ], 500);
        }
    }

    /**
     * 生成邀请链接
     */
    public function generateInviteLink(Request $request, $id)
    {
        try {
            $user = Auth::user();

            // 验证账本权限（只有管理员可以邀请）
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id)
                      ->where('role', MoneyBookUser::ROLE_ADMIN);
            })->findOrFail($id);

            // 检查账本创建者是否为会员
            $creator = User::find($book->user_id);
            if (!$creator->isMember()) {
                // 非会员账本，检查当前成员数量是否已达上限
                $currentMemberCount = $book->users()->count();
                $maxMembers = non_member_limits['max_books_user'];

                if ($currentMemberCount >= $maxMembers) {
                    return response()->json([
                        'success' => false,
                        'message' => '非会员账本最多只能' . $maxMembers . '位成员，请升级会员后继续添加',
                        'redirect_to' => route('membership.benefits')
                    ], 422);
                }
            }

            // 创建邀请记录
            $invitation = BookInvitation::createInvitation($book->id, $user->id);

            // 生成邀请链接
            $inviteUrl = url('/invite/' . $invitation->token);

            return response()->json([
                'success' => true,
                'message' => '邀请链接生成成功',
                'invite_url' => $inviteUrl,
                'expires_at' => $invitation->expires_at->format('Y-m-d H:i:s')
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '生成邀请链接失败，请重试'
            ], 500);
        }
    }

    /**
     * 显示邀请页面
     */
    public function showInvite($token)
    {
        $invitation = BookInvitation::with(['book', 'inviter'])
                                   ->where('token', $token)
                                   ->first();

        if (!$invitation) {
            abort(404, '邀请链接不存在');
        }

        // 检查邀请是否过期或已使用
        if (!$invitation->isValid()) {
            // 如果邀请已过期或已使用，显示过期页面
            return view('invite.expired', compact('invitation'));
        }

        // 邀请有效，显示邀请详情页面
        return view('invite.show', compact('invitation'));
    }

    /**
     * 接受邀请
     */
    public function acceptInvite(Request $request, $token)
    {
        try {
            $user = Auth::user();

            $invitation = BookInvitation::with('book')
                                       ->where('token', $token)
                                       ->first();

            if (!$invitation) {
                return response()->json([
                    'success' => false,
                    'message' => '邀请链接不存在'
                ], 404);
            }

            if (!$invitation->isValid()) {
                return response()->json([
                    'success' => false,
                    'message' => '邀请链接已过期或已使用'
                ], 422);
            }

            // 检查用户是否已在账本中
            $existingUser = MoneyBookUser::where('book_id', $invitation->book_id)
                                        ->where('user_id', $user->id)
                                        ->first();
            if ($existingUser) {
                return response()->json([
                    'success' => false,
                    'message' => '您已经是该账本的成员'
                ], 422);
            }

            // 检查账本创建者是否为会员
            $creator = User::find($invitation->book->user_id);
            if (!$creator->isMember()) {
                // 非会员账本，检查当前成员数量是否已达上限
                $currentMemberCount = $invitation->book->users()->count();
                $maxMembers = non_member_limits['max_books_user'];

                if ($currentMemberCount >= $maxMembers) {
                    return response()->json([
                        'success' => false,
                        'message' => '该账本已达到非会员可添加的最大成员数量(' . $maxMembers . '人)，请联系邀请人升级会员后再加入',
                        'redirect_to' => route('membership.benefits'),
                    ], 422);
                }
            }

            // 使用邀请
            $invitation->use($user->id);

            // 添加用户到账本
            MoneyBookUser::create([
                'book_id' => $invitation->book_id,
                'user_id' => $user->id,
                'role' => MoneyBookUser::ROLE_MEMBER,
            ]);

            return response()->json([
                'success' => true,
                'message' => '成功加入账本',
                'book' => [
                    'id' => $invitation->book->id,
                    'name' => $invitation->book->name,
                    'description' => $invitation->book->description,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '加入账本失败，请重试'
            ], 500);
        }
    }

    /**
     * 获取账本成员列表
     */
    public function getMembers($bookId)
    {
        try {
            $user = Auth::user();

            // 验证用户是否有权限访问该账本
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            $members = $book->users()->get()->map(function($member) use ($book) {
                return [
                    'id' => $member->id,
                    'name' => $member->name,
                    'email' => $member->email,
                    'phone' => $member->phone,
                    'role' => $member->pivot->role,
                    'is_creator' => $book->user_id == $member->id,
                    'joined_at' => $member->pivot->created_at->format('Y-m-d H:i:s')
                ];
            });

            return response()->json([
                'success' => true,
                'members' => $members,
                'creator_id' => $book->user_id
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取成员列表失败'
            ], 500);
        }
    }

    /**
     * 移除账本成员
     */
    public function removeMember(Request $request, $bookId, $userId)
    {
        try {
            $user = Auth::user();

            // 验证用户是否有权限访问该账本
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            // 检查当前用户是否为账本创建者或管理员
            $currentUserRole = $book->users()->where('user_id', $user->id)->first()->pivot->role;
            if ($book->user_id !== $user->id && $currentUserRole !== MoneyBookUser::ROLE_ADMIN) {
                return response()->json([
                    'success' => false,
                    'message' => '您没有权限移除成员'
                ], 403);
            }

            // 检查要移除的用户是否为账本创建者
            if ($book->user_id == $userId) {
                return response()->json([
                    'success' => false,
                    'message' => '不能移除账本创建者'
                ], 403);
            }

            // 检查要移除的用户是否在账本中
            $memberToRemove = $book->users()->where('user_id', $userId)->first();
            if (!$memberToRemove) {
                return response()->json([
                    'success' => false,
                    'message' => '该用户不在账本中'
                ], 404);
            }

            // 移除用户
            $book->users()->detach($userId);

            // 如果被移除的用户将该账本设为默认账本，则清除其默认账本设置
            $removedUser = User::find($userId);
            if ($removedUser && $removedUser->default_book_id == $bookId) {
                $removedUser->update(['default_book_id' => null]);
            }

            return response()->json([
                'success' => true,
                'message' => '成员移除成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '移除成员失败，请重试'
            ], 500);
        }
    }

    /**
     * 显示分类管理页面
     */
    public function categoryManagement($bookId)
    {
        try {
            $user = Auth::user();

            // 验证用户是否有权限访问该账本
            $book = MoneyBook::whereHas('users', function($query) use ($user) {
                $query->where('user_id', $user->id);
            })->findOrFail($bookId);

            return view('user.category-management', compact('book'));
        } catch (\Exception $e) {
            return redirect()->route('user.books')->with('error', '账本不存在或无权限访问');
        }
    }
}
